package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import com.hmdp.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Blog queryBlogById(Long id) {
        Blog blog = getById(id);
        if(blog==null){
            log.error("笔记不存在！");
        }
        //查询博客同时还要查询用户信息
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        //同时查询是否被点过赞
        isBlogLiked(blog);
        return blog;
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{    //函数当做参数传递给方法
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());

            this.isBlogLiked(blog);//上面查询用户信息的四行也可以单独封装成一个函数
        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        //获取登录用户
        UserVO userVO = UserHolder.getUser();
        Long userId = userVO.getId();
        //判断当前登录用户是否已经点赞(改为在redis的zset集合中查！！！）
        String key= RedisConstants.BLOG_LIKED_KEY+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score==null) {
            //如果未点赞，进行点赞,数据库liked字段属性+1,
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            //如果DB更新成功，再保存用户到zset集合
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());//每次点赞时的用户记录点赞时间戳，作为排序依据
            }
        }
        //已经点赞，数据库liked-1，把用户从zset集合删除
        boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
        if (isSuccess) {
            stringRedisTemplate.opsForZSet().remove(key,userId.toString());//stringRedisTemplate.delete是直接删除键！
        }
        return Result.ok();
    }

    @Override
    public Result queryBloglikes(Long id) {
        //查询top5的点赞用户 zrange key 0 4
        String key= RedisConstants.BLOG_LIKED_KEY+id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5==null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        // 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<UserVO> userVOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserVO.class))
                .collect(Collectors.toList());
        //返回
        return Result.ok(userVOS);
    }

    /**
     * 查询博客是否被点过赞，并设置是否点赞的属性初始值为true或false
     */
    private void isBlogLiked(Blog blog){
        //获取登录用户
        UserVO userVO = UserHolder.getUser();
        if(userVO==null){
            return;
        }
        Long userId = userVO.getId();
        //判断当前登录用户是否已经点赞(在redis的set集合中查！！！）
        String key="blog:like"+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);//有时间戳则点赞了，设置为true
    }
}
